// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { roomId, action, data } = event
  
  try {
    // 查找房间
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()
    
    if (room.data.length === 0) {
      return {
        success: false,
        error: '房间不存在'
      }
    }
    
    const roomData = room.data[0]
    
    // 检查房间状态
    if (roomData.status !== 'playing') {
      return {
        success: false,
        error: '游戏未开始'
      }
    }
    
    // 检查玩家权限
    const isPlayer = roomData.players.some(player => player.openid === wxContext.OPENID)
    if (!isPlayer) {
      return {
        success: false,
        error: '非游戏玩家'
      }
    }
    
    // 根据不同的操作类型更新游戏数据
    let updateData = {
      lastUpdateTime: db.serverDate()
    }
    
    switch (action) {
      case 'rollDice':
        // 更新骰子结果
        updateData['gameData.currentPlayer'] = wxContext.OPENID
        updateData['gameData.diceResult'] = data.result
        break
        
      case 'selectQuestion':
        // 更新选择的问题
        updateData['gameData.currentQuestion'] = data.question
        break
        
      case 'submitAnswer':
        // 更新答案
        updateData['gameData.currentAnswer'] = data.answer
        updateData['gameData.results'] = db.command.push({
          round: roomData.gameData.currentRound,
          player: wxContext.OPENID,
          answer: data.answer,
          time: db.serverDate()
        })
        break
        
      case 'nextRound':
        // 进入下一回合
        updateData['gameData.currentRound'] = roomData.gameData.currentRound + 1
        updateData['gameData.currentPlayer'] = null
        updateData['gameData.diceResult'] = null
        updateData['gameData.currentQuestion'] = null
        updateData['gameData.currentAnswer'] = null
        
        // 检查游戏是否结束
        if (updateData['gameData.currentRound'] >= roomData.gameData.totalRounds) {
          updateData.status = 'finished'
        }
        break
        
      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
    
    // 更新房间数据
    await db.collection('rooms').where({
      roomId: roomId
    }).update({
      data: updateData
    })
    
    return {
      success: true,
      roomData: {
        ...roomData,
        ...updateData
      }
    }
  } catch (error) {
    console.error('同步游戏数据失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 